package com.uoko.common.math;



import java.util.Random;

/**
 * <p>
 * 产生随机数
 * </p>
 *
 * @author shaohua
 * Email xiaomabenten@gamil.com
 * created by 2018/6/7
 */

public class Randoms {
    private static final int MAX_LENGTH = 50;

    /**
     * 随机生成 length 长度的数据
     *
     * @param length
     * @return
     */
    public static String createComplexCode(int length) {
        if (length > MAX_LENGTH) {
            length = MAX_LENGTH;
        }
        Random random = new Random();
        StringBuilder code = new StringBuilder();
        while (true) {
            if (code.length() == length) {
                break;
            }
            int tmp = random.nextInt(127);
            if (tmp < 33 || tmp == 92 || tmp == 47 || tmp == 34) {
                continue;
            }
            char x = (char) tmp;
            if (code.toString().indexOf(x) > 0) {
                continue;
            }
            code.append(x);
        }
        return code.toString();
    }

    /**
     * 随机产生 length 长度的数字
     *
     * @param length
     * @return
     */
    public static String createNumberCode(int length) {
        return randomString("0123456789", length);
    }

    private static String randomString(String baseString, int length) {
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        if (length < 1) {
            length = 1;
        }
        int baseLength = baseString.length();
        for (int i = 0; i < length; ++i) {
            int number = random.nextInt(baseLength);
            sb.append(baseString.charAt(number));
        }

        return sb.toString();
    }
}
